package com.huc.rabbit.mq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    @Value("${mq.exchange}")
    private String exchange;

    @Value("${mq.ingate.queue}")
    private String ingateQueue;


    @Bean
    public Queue ingateQueue() {
        return new Queue(ingateQueue);
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(exchange);
    }

    @Bean
    public Binding bindIngateQueue2Exchange() {
        return BindingBuilder.bind(ingateQueue()).to(exchange()).withQueueName();
    }

    @Bean("rabbitTransactionManager")
    public RabbitTransactionManager rabbitTransactionManager(CachingConnectionFactory cachingConnectionFactory) {
        return new RabbitTransactionManager(cachingConnectionFactory);
    }


//    @Bean
//    public RabbitTemplate rabbitTemplate() {
//        // 消息发送失败返回到队列中, yml需要配置 publisher-returns: true
//        rabbitTemplate.setMandatory(true);
//
//        // 消息返回, yml需要配置 publisher-returns: true
//        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
//            String correlationId = message.getMessageProperties().getCorrelationId();
//            System.out.println("消息发送失败:" + message + " ---> " + correlationId);
//        });
//
//        // 消息确认, yml需要配置 publisher-confirms: true
//        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
//            if (ack) {
//                System.out.println("correlationData:" + correlationData);
//                System.out.println("ack:" + ack);
//                System.out.println("cause:" + cause);
//            } else {
//                System.out.println("ack:" + ack);
//            }
//        });
//
//        return rabbitTemplate;
//    }


}
